﻿using CsvHelper.Configuration;
using log4net;
using Lottery.Classes;
using Lottery.Error;
using Lottery.Model;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;

namespace Lottery.Data
{
    public class GiftData
    {
        private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        private static GiftData instances = null;

        public static GiftData Instances
        {
            get
            {
                if (instances == null)
                    instances = new GiftData();
                return GiftData.instances;
            }
        }

        private List<GiftInfo> gifts = new List<GiftInfo>();

        private GiftData()
        {
            if (gifts == null || gifts.Count <= 0)
            {
                this.reload();
            }
        }

        public void reload()
        {
            this.gifts.Clear();
            this.gifts = this.loadGifts(MyResources.GetConfigPath(MyResources.GiftsName));

        }





        //当前日期，sufei 2013/12/9
        private static DateTime dt = System.DateTime.Now;//获得今天的日期
        private TimeSpan ts1 = new TimeSpan(dt.Ticks);//将当前日期转化为可以比较的类型,sufei 2013/12/9

        private String nowDateStr = dt.ToString("yyyy-MM-dd", DateTimeFormatInfo.InvariantInfo);

        private List<GiftInfo> loadGifts(string fileName)
        {
            //  Dictionary<int, List<GiftInfo>> gifts = new Dictionary<int, List<GiftInfo>>();
            // List<String> wingift = this.loadWingifts(MyResources.GetConfigPath(MyResources.WinnersName));
            TxtData<GiftInfo> txtData = new TxtData<GiftInfo>(MyResources.GetConfigPath(MyResources.GiftsName));
            txtData.SkipLine = 3;
            txtData.ClassMap = typeof(GiftInfoMap);
            List<GiftInfo> allGiftInfos = txtData.readToObject();

            foreach (GiftInfo gift in allGiftInfos)
            {
                //从中奖名单中获取已经
                gift.OddNumber = gift.Number - WinnerData.Instances.existGift(gift.Name);
                if (String.IsNullOrEmpty(gift.EffectiveDate))
                {
                    gift.EffectiveDate = nowDateStr;
                }
                if (gift.OddNumber > 0 && gift.EffectiveDate.Equals(nowDateStr))
                {
                    if (gift.Batch <= 0)
                    {
                        gift.Batch = 1;
                    }

                    gift.Number = gift.OddNumber;
                    this.gifts.Add(gift);
                    //if (gifts.ContainsKey(gift.Level))
                    //    gifts[gift.Level].Add(gift);
                    //else
                    //   gifts.Add(gift.Level, new List<GiftInfo>() { gift });

                }
            }
            //this.startIndex(gifts);//为gifts快速排序
            this.gifts = this.gifts.OrderByDescending(g => g.Level).ToList<GiftInfo>();
            return gifts;
        }

        public sealed class GiftInfoMap : ClassMap<GiftInfo>
        {
            public GiftInfoMap()
            {
                Map(m => m.Level).Name("等级");
                Map(m => m.LevelName).Name("等级描述");
                Map(m => m.Name).Name("奖品");
                Map(m => m.Number).Name("数量");
                Map(m => m.Unit).Name("单位");
                //Map(m => m.Value).Name("价值");
                Map(m => m.OddNumber).Name("剩余");
                Map(m => m.EffectiveDate).Name("生效日期");
                Map(m => m.Batch).Name("批量抽取");
            }
        }



        public GiftInfo RandomGift
        {
            get
            {
                if (this.gifts.Count <= 0)
                {
                    throw new NoneGiftError();
                }
                GiftInfo gift = this.gifts.FirstOrDefault();
                //如果该奖品没有数量了
                if (gift.OddNumber <= 0)
                {
                    //删除这个奖品
                    this.removeGiftNum(gift);
                    //进入下一个随机
                    return this.RandomGift;
                }
                // Dictionary<int, List<GiftInfo>> gifts
                Console.WriteLine("抽取奖品{0}，等级{1}，剩余数量为{2}", gift.Name, gift.Level, gift.Number);
                gift.GiftIndex = System.Guid.NewGuid().ToString();
                return gift;
            }
        }

        public GiftInfo NextGift
        {
            get
            {
                return RandomGift;
            }
        }



        /// <summary>
        /// 移除已经抽中的奖品
        /// </summary>
        /// <param name="level"></param>
        /// <param name="index"></param>
        public void removeGiftNum(GiftInfo giftInfo)
        {
            try
            {
                if (giftInfo == null)
                    return;
                giftInfo.OddNumber--;
                if (giftInfo.OddNumber <= 0)
                {
                    log.InfoFormat("奖品抽完了删掉:{0},{1}", giftInfo.LevelName, giftInfo.Name);
                    this.gifts.Remove(giftInfo);
                }

            }
            catch (Exception e)
            {
                log.Error(e);
            }
        }




    }
}
